package cc.facesign.admin.service.impl;

import cc.facesign.admin.bean.StaConfSign;
import cc.facesign.admin.bean.TblConfUser;
import cc.facesign.admin.bean.vo.ConfSignVo;
import cc.facesign.admin.mapper.StaConfSignMapper;
import cc.facesign.admin.service.StaConfSignService;
import cc.facesign.admin.service.TblConfUserService;
import cc.facesign.admin.utils.PowerUtils;
import cc.facesign.servicebase.utils.RedisCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-05-09
 */
@Transactional
@Service
public class StaConfSignServiceImpl extends ServiceImpl<StaConfSignMapper, StaConfSign> implements StaConfSignService {

    @Autowired
    private PowerUtils powerUtils;

    @Autowired
    private StaConfSignService staConfSignService;

    @Autowired
    private TblConfUserService confUserService;

    @Autowired
    private RedisCache redisCache;
    @Transactional
    @Override
    public List<ConfSignVo> getByDate(Date date) {
        String userId = powerUtils.getCurrentUser().getId();
        String key = "sta:conf:"+userId+":"+date;
        String setKey = "user:manage:dept-set:"+userId;
        HashSet<String> set = powerUtils.getCurrentChildConfIdSet();

        Set<String> cacheSet = redisCache.getCacheSet(setKey);
        List<ConfSignVo> list = redisCache.getCacheList(key);

        // 用户管理的部门没有发生改变、查询日期为之前的日期、redis的数据不为空
        if (cacheSet.equals(set) && date.compareTo(new Date()) < 0 && list != null) {
            return list;
        }

        List<ConfSignVo> infoList = baseMapper.getInfoByDate(date);
        List<StaConfSign> tbls = new ArrayList<>();
        for (ConfSignVo e : infoList) {
            QueryWrapper<TblConfUser> w = new QueryWrapper<>();
            w.eq("conf_id", e.getConfId());
            w.eq("is_sign", 1);
            int sign = confUserService.count(w);

            e.setSign(sign);
            e.setRate((double)e.getTotal() / sign);

            StaConfSign t = new StaConfSign();
            BeanUtils.copyProperties(e, t);
            tbls.add(t);
        }

        // 信息存入数据库
        staConfSignService.saveOrUpdateBatch(tbls);
        // 存入redis
        redisCache.setCacheList(key ,infoList);
        // 更新用户管理的部门
        redisCache.setCacheSet(setKey, set);

        return infoList;
    }
}
